﻿@using Page = viBook.Models.Page
@model Page
<script id="AllPageTemplate" type="text/html">
    <a data-bind="attr: {href: '/Pages/Edit/' + Id}">
    <img data-bind="attr: {src: ImageSource}" style="width: 60px"/>
    </a>
</script>
<script id="ChapterTemplate" type="text/html">
    <img class="picture-small cropable" data-bind="attr: {src: src}"></img>
</script>
<script id="TagTemplate" type="text/html">
    <div id="tag-box" class="tag_label tag_label tag_label_inactive" data-bind="style:{marginTop: y,marginLeft:x,width:w,height:h}">
        <a href="#" data-bind="click: removeTag">Delete</a>
@*        <a href="#" class="edit-hyperlink"  data-bind="click: editText">Edit text</a>*@
        <br/>
        <span class="translatedText">${translatedText}</span>
    </div>
</script>
<script type="text/javascript">
 $(function() {
     $("#foo2").carouFredSel({
             curcular: false,
             infinite: false,
             auto: false,
             height:120,
             prev: {
                 button: "#foo2_prev",
                 key: "left"
             },
             next: {
                 button: "#foo2_next",
                 key: "right",
                 padding: 200
             }
         });
 });
google.load("language", "1");

function onGoogleTranslateLoaded() {
    var languages = google.language.Languages;
    var languageCollection = [];
    for (var propName in languages) {
        if (languages.hasOwnProperty(propName)) {
            languageCollection[languageCollection.length] = new Language(ToFirstUpperCase(propName), $(languages).prop(propName));
        }
    }
    viewmodel.languages(languageCollection);
    viewmodel.selectedLanguageFrom(languageCollection[24]);
    viewmodel.selectedLanguageTo(languageCollection[105]);
}

function ToFirstUpperCase(str) {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

function ParseRect(positionStr) {
    var positionArray = positionStr.split("_");
    return {
        x: parseInt(positionArray[0]),
        y: parseInt(positionArray[1]),
        w: parseInt(positionArray[2]),
        h: parseInt(positionArray[3])
    };
}

function Picture(id, src) {
    return {
        id: id,
        src: ko.observable(src)
    };
}

function Page(id, number, imageSource) {
    return {
        Id: id,
        Number: number,
        ImageSource: imageSource
    };
}

function Tag(id, positionStr, convertedText, translatedText) {
    var rec = ParseRect(positionStr);
    return {
        id: id,
        positionStr: positionStr,
        y: ko.observable(rec.y + 'px'),
        x: ko.observable(rec.x + 'px'),
        x2: ko.observable((rec.x + rec.w) + 'px'),
        w: ko.observable(rec.w + 'px'),
        h: ko.observable(rec.h + 'px'),
        convertedText: ko.observable(convertedText),
        translatedText: ko.observable(translatedText),
        pageId: @Model.Id ,
        pageUrl: '@Model.ImageSource',
        removeTag: function() {
            viewmodel.tagCollection.remove(this);
            if (this.id > 0) {
                viewmodel.deletedTags.push(this.id);
            } else {
                var currentTag = this;
                viewmodel.addedTags.remove(function(item) {
                    return item.id == currentTag.id;
                });
            }
        },
        editText: function() {
            edittingTagItemId = this.id;           
            $('#converted-text').val(this.convertedText());
            $('#translated-text').val(this.translatedText());
            $("a#button-save-tag").fancybox().trigger('click');
        }
    };
}

function Language(displayName, googleCode) {
    return {
        displayName: displayName,
        googleCode: googleCode
    };
}

var newlyCreatedTagId = -1,
    edittingTagItemId,
    allConvertLanguages = @CustomHelpers.RenderLanguages() ,
    initialPicture = @CustomHelpers.PageToJavaScriptConverter(Model) ,
    initialTags = @CustomHelpers.TagsToJavaScriptConverter(Model.Tags.ToList()) ,
    allPagesInfo = @CustomHelpers.PageCollectionToJavaScriptConverter(Model.AllPages.ToList()) ,
    jcropApi,
    viewmodel = {
        picture: ko.observable(initialPicture),
        allPagesCollection: ko.observableArray(allPagesInfo),
        tagCollection: ko.observableArray(initialTags),
        convertLanguages: ko.observableArray(allConvertLanguages),
        selectedConvertLanguage: ko.observableArray(),
        languages: ko.observableArray(),
        selectedLanguageFrom: ko.observable(),
        selectedLanguageTo: ko.observable(),
        deletedTags: ko.observableArray([]),
        addedTags: ko.observableArray([]),
        isShowButtonSaveAll: function() {
            return (this.addedTags().length + this.deletedTags().length) > 0;
        },
        createNewTag: function() {
            edittingTagItemId = 0;
            jcropApi = $.Jcrop('.cropable');
            $('#button-init-tag').hide();
            $('#button-destroy-tag').show();
            $('#button-save-tag').show();
        },
        cancelTag: function() {
            $('#button-init-tag').show();
            $('#button-destroy-tag').hide();
            $('#button-save-tag').hide();
            jcropApi.destroy();
            $('#add-tag-modal').trigger('click');
        },
        saveTag: function() {
            $('#add-tag-div').show();
            $('#button-destroy-tag').hide();
            $('#button-save-tag').hide();
            $('#add-tag-modal').toggle();
            $.fancybox.close();
        },
        finishSaveTag: function() {
            var sel = jcropApi.tellSelect(),
                position = sel.x + '_' + sel.y + '_' + sel.w + '_' + sel.h,
                convertedText = $('#converted-text').val(),
                translatedText = $('#translated-text').val(),
                newTag = new Tag(newlyCreatedTagId, position, convertedText, translatedText),
                added = {
                    id: newlyCreatedTagId,
                    position: position,
                    convertedText: convertedText,
                    translatedText: translatedText
                };
            viewmodel.addedTags.push(added);
            viewmodel.tagCollection.push(newTag);
            newlyCreatedTagId--;
            $('#button-init-tag').show();
            $('#add-tag-div').hide();
            $('#add-tag-modal').hide();
            $.fancybox.close();
            jcropApi.destroy();
            $('#converted-text').val("");
            $('#translated-text').val("");
        },
        cancelSaveTag: function() {
            $('#button-init-tag').show();
            $('#add-tag-modal').hide();
            $.fancybox.close();
            jcropApi.destroy();
            $('#converted-text').val("");
            $('#translated-text').val("");
        },
        saveAll: function() {
            $.ajax({
                    url: '@Url.Action("SaveTags", "Pages")',
                    type: 'POST',
                    data: ko.toJSON({ deleted: viewmodel.deletedTags(), added: viewmodel.addedTags(), pageId: @Model.Id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.success) {
                            viewmodel.addedTags.removeAll();
                            viewmodel.deletedTags.removeAll();
                        } else {
                            window.ShowError(result.message);
                        }
                    }
                });
        },
        fetchNextPicture: function() {
            $.ajax({
                    url: '@Url.Action("FetchNextCommentPage", "ChapterComments")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo() + 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var listComment = [];
                            $(result.comments).each(function(index, item) {
                                listComment[index] = new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
                            });
                            viewmodel.commentCollection(listComment);
                            viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
                            viewmodel.isDisablePrevBtn(viewmodel.commentPageNo() == 1);
                            viewmodel.isDisableNextBtn(viewmodel.commentPageNo() == viewmodel.totalCommentPage());
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        convert: function() {
            var sel = jcropApi.tellSelect(),
                position = sel.x + '_' + sel.y + '_' + sel.w + '_' + sel.h;
            $.ajax({
                    url: '@Url.Action("ConvertText", "Pages")',
                    type: 'POST',
                    data: ko.toJSON({ imageUrl: '@Model.ImageSource', position: position, language: viewmodel.selectedConvertLanguage().googleCode }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.success) {
                            $('#converted-text').val(result.text);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        translate: function() {
            google.language.translate($('#converted-text').val(), viewmodel.selectedLanguageFrom().googleCode, viewmodel.selectedLanguageTo().googleCode, function(result) {
                if (result.translation) {
                    $('#translated-text').val(result.translation);
                } else {
                    $('#translated-text').val($('#converted-text').val());
                }
            });
        }
    };

ko.applyBindings(viewmodel);
$("a#button-save-tag").fancybox({
        'modal': false,
        'showCloseButton': false,
        'hideOnOverlayClick': false,
        'width': 485,
        'height': 390,
        'autoDimensions': false
    });
google.setOnLoadCallback(onGoogleTranslateLoaded);
</script>
